package com.example.demo.demos.resource;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.server.McpServerFeatures;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.FileCopyUtils;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Configuration
public class SystemInfoResource {
    @Bean
    public List<McpServerFeatures.AsyncResourceSpecification> myResources() {
        McpSchema.Resource systemInfoResource = new McpSchema.Resource("test.txt", "firstTestResource", "resouce demo", "plain/txt"
                , new McpSchema.Annotations(Arrays.asList(McpSchema.Role.USER), 0.7));
        McpServerFeatures.AsyncResourceSpecification resourceSpecification = new McpServerFeatures.AsyncResourceSpecification(systemInfoResource, (exchange, request) -> {
            try {
                Map systemInfo = Map.of("data"
                        , new String(FileCopyUtils.copyToByteArray(new PathMatchingResourcePatternResolver().getResource("/test.txt").getInputStream())));
                String jsonContent = new ObjectMapper().writeValueAsString(systemInfo);
                McpSchema.ReadResourceResult r = new McpSchema.ReadResourceResult(
                        Arrays.asList(new McpSchema.TextResourceContents(request.
                                uri(), "application/json", jsonContent)));
                return Mono.just(r);
            } catch (Exception e) {
                throw new RuntimeException("Failed to generate system info", e);
            }
        });

        return Arrays.asList(resourceSpecification);
    }
}
